﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;

namespace GRWL.BZSC.UI
{
    public partial class QCFrm : BaseFrm
    {
        public int tb_qc_id;//当前的id号

        ///// <summary>
        ///// 记住当前设置的编码规则
        ///// </summary>
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        //// 单据编辑状态
        //public GRWL.BZSC.UI.Common.BillOperateType EditStatus;

        public enum CheckType
        {
            /// <summary>
            /// 采购检验
            /// </summary>
            采购检验,
            /// <summary>
            /// 生产检验
            /// </summary>
            生产检验
        }

        public CheckType BillType { get; set; }

        ///// <summary>
        ///// 单据编号字头
        ///// </summary>
        //private string BillPrefix;

        //private XQC xMain;
        //private XQCDetail[] xDetials;
        //private TB_Trader Trader;
        //private TB_Department Department;
        private TB_Department[] Departments;

        #region 检查字符串是否只为数字
        private bool isNumber(string str)
        {
            if (str == "")
                return false;
            int flag = 0;
            char[] c = str.ToCharArray();
            for (int i = 0; i < str.Length; i++)
            {
                if (Char.IsNumber(str[i]) || str[i] == '.')
                {
                    flag++;
                }
                else
                {
                    flag = -1;
                    break;
                }
            }
            if (flag > 0)
                return true;
            else
                return false;
        }
        #endregion 

        private void setReadOnly(bool b)
        {
            for (int i = 0; i < this.gvQCDetail.Columns.Count; i++)
            {
                if (b && (this.gvQCDetail.Columns[i].Name == "checkNum" || this.gvQCDetail.Columns[i].Name == "deliveryNum" 
                    || this.gvQCDetail.Columns[i].Name == "conclusion" || this.gvQCDetail.Columns[i].Name == "traderComment" || this.gvQCDetail.Columns[i].Name == "craftComment"
                    || this.gvQCDetail.Columns[i].Name == "memo" || this.gvQCDetail.Columns[i].Name == "refundNum" || this.gvQCDetail.Columns[i].Name == "QcResultName"
                    || this.gvQCDetail.Columns[i].Name == "CraftComment" || this.gvQCDetail.Columns[i].Name == "OperatorName"))
                {
                    this.gvQCDetail.Columns[i].ReadOnly = false;
                }
                else
                {
                    this.gvQCDetail.Columns[i].ReadOnly = true;
                }
            }
        }

        private bool bGraph = false;

        private void bindOperatorName()
        {
            //TB_User[] TB_User = this.BaseDataProxy.findq();

            //TB_QCProblemType[] tbQCProblem = this.BaseDataProxy.FindQCProblemTypes();
            //DataTable dtQCProblem = tbQCProblem.ToDataTable();

            //this.name.Items.Add("[]");
            //for (int i = 0; i < dtQCProblem.Rows.Count; i++)
            //{
            //    this.name.Items.Add(dtQCProblem.Rows[i]["name"] + "[" + dtQCProblem.Rows[i]["id"] + "]");
            //}

        }

        private void bindQCProblem()
        {
            TB_QCProblemType[] tbQCProblem = this.BaseDataProxy.FindQCProblemTypes();
            DataTable dtQCProblem = tbQCProblem.ToDataTable();

            this.name.Items.Add("[]");
            for (int i = 0; i < dtQCProblem.Rows.Count; i++)
            {
                this.name.Items.Add(dtQCProblem.Rows[i]["name"] + "[" + dtQCProblem.Rows[i]["id"] + "]");
            }

        }

        private void bindQCResult()
        {
            TB_QCResult[] tbQCResult = this.BaseDataProxy.FindQCResults();
            DataTable dtQCResult = tbQCResult.ToDataTable();

            this.QcResultName.Items.Clear();
            this.QcResultName.Items.Add("[]");
            for (int i = 0; i < dtQCResult.Rows.Count; i++)
            {
                this.QcResultName.Items.Add(dtQCResult.Rows[i]["result"] + "[" + dtQCResult.Rows[i]["id"] + "]");
            }

        }

        public QCFrm()
        {
            InitializeComponent();
            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();
            this.codeRule = new CodeRuleFrm.CodeRule();
            EditStatus = Common.BillOperateType.None;
            this.Text = "采购质检单";
            BillPrefix = "ZJ";            
        }

        private void frmQC_Load(object sender, EventArgs e)
        {
            DisabledControls();
            Departments = BaseDataProxy.FindDepartments(null,null,null);
            bindQCProblem();
            //bindQCResult();

            if (BillType == CheckType.生产检验)
            {
                this.Text = "生产质检单";
                BillPrefix = "SCZJ";
            }
        }

        private void GetControlsData()
        {
            tMain.Rows[0]["code"] = txtDjh.Text;
            tMain.Rows[0]["createTime"] = dtpqcDate.Value;
            tMain.Rows[0]["OperatorName"] = txtOperator.Text;
            tMain.Rows[0]["AssessorName"] = txtAssessor.Text;
            tMain.Rows[0]["status"] = txtStatus.Text;
            //traderSelector
            tMain.Rows[0]["address"] = txtJyType.Text;
            //departmentUTextBox
            tMain.Rows[0]["memo"] = txtMemo.Text;
        }

        private void DisabledControls()
        {
            SetControlsStatus(false);
        }

        private void EnabledControls()
        {
            SetControlsStatus(true);
        }

        private void SetControlsStatus(bool SetEnagledFlag)
        {
            txtDjh.Enabled = SetEnagledFlag;
            dtpqcDate.Enabled = SetEnagledFlag;
            //operatorUTextBox.Enabled = SetEnagledFlag;
            //assessorUTextBox.Enabled = SetEnagledFlag;
            //statusUTextBox.Enabled = SetEnagledFlag;
            edtTrader.Enabled = SetEnagledFlag;
            //BillTypeUTextBox.Enabled = SetEnagledFlag;
            txtMemo.Enabled = SetEnagledFlag;

            gvQCDetail.ReadOnly = !SetEnagledFlag;
            setReadOnly(SetEnagledFlag);
        }

        private void SetNull()
        {
            tMain.Clear();
            tDetail.Clear();

            this.txtDjh.Text = "";
            this.txtOperator.Text = "";
            this.txtMender.Text = "";
            this.txtStatus.Text = "";
            this.txtMemo.Text = "";
            this.txtJyType.Text = "";
            this.txtAssessor.Text = "";

            for (int i = gvQCDetail.Rows.Count - 1; i >= 0; i--)
            {
                gvQCDetail.Rows.RemoveAt(i);
            }
            for (int i = gvQCPromble.Rows.Count - 2; i >= 0; i--)
            {
                gvQCPromble.Rows.RemoveAt(i);
            }

            EditStatus = Common.BillOperateType.None;
 
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            //放弃新单
            if (tMain.Rows.Count > 0)
            {
                if (MessageBox.Show("是要放弃当前单据，重新新增一张单吗？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }

            //新单输入
            SetNull();
            SetControlsStatus(true);
            btnSelect.Enabled = true;
            btnConfirm.Enabled = false;
            EditStatus = Common.BillOperateType.Add;

            tMain.Clear();
            DataRow NewMainRow = tMain.NewRow();
            // SH - 收货单号字头
            //this.txtDjh.Text = BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
            //NewMainRow["code"] = this.txtDjh.Text;
            NewMainRow["operator"] = SysLoginUserInfo.UserId;
            this.txtOperator.Text = SysLoginUserInfo.UserName;
            NewMainRow["createTime"] = DateTime.Now;
            //NewMainRow["type"] = BillPrefix;
            NewMainRow["status"] = "未批";
            this.txtStatus.Text = "未批";
            tMain.Rows.Add(NewMainRow);

            //this.btnAppend.Enabled = false;

            //tDetail.Clear();
            //DataRow NewDetailRow = tDetail.NewRow();
            //tDetail.Rows.Add(NewDetailRow);

            //SetControlsData();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (tMain.Rows.Count > 0)
            {
                if (MessageBox.Show("是要放弃当前单据，重新打开一张单据吗？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }

            bGraph = true;

            #region 清空数据
            SetNull();
            #endregion

            //加载打开单据
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.CGZJ;
            frm.SearchMode = GRWL.BZSC.UI.FindBillFrm.SearchModeType.open;

            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    QQC qqc = OTConverter.ConvertToObject<QQC>(frm.SelectedItems);
                    tb_qc_id = qqc.Id;
                    OpenBill(qqc.Id);
                }
            }

            //SelectBillFrm frm = new SelectBillFrm();
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.ZJ, BillPrefix, false);
            //frm.ShowDialog();

            //if (frm.SelectBills.Count > 0)
            //{
            //    OpenBill(frm.SelectBills[0].BillId);
            //    tb_qc_id = frm.SelectBills[0].BillId;
            //}

            bGraph = false;
        }

        private void OpenBill(int BillId)
        {

            XQC tm = BaseDataProxy.GetXQC(BillId);
            XQCDetail[] td = BaseDataProxy.GetXQCDetials(BillId);

            #region
            if (tm != null)
            {
                tMain.Clear();
                DataRow NewMainRow = tMain.NewRow();
                NewMainRow["id"] = tm.QC.id;
                
                NewMainRow["code"] = tm.QC.code;
                this.txtDjh.Text = tm.QC.code;

                if (tm.QC.qcDate != null)
                {
                    NewMainRow["qcDate"] = tm.QC.qcDate;
                    this.dtpqcDate.Value = Convert.ToDateTime(tm.QC.qcDate);
                }

                NewMainRow["type"] = tm.QC.type;
                if (tm.QC.type == "CGZJ")
                    this.txtJyType.Text = "采购检验";
                else if (tm.QC.type == "SCZJ")
                    this.txtJyType.Text = "生产检验";
                

                if (tm.QC.trader != null)
                {
                    SelectItem item = new SelectItem();
                    item.Name = tm.TraderName;
                    item.Key = tm.TraderCode;
                    item.Value = tm.QC.trader.ToString();
                    this.edtTrader.SetSelected(item);

                    NewMainRow["trader"] = tm.QC.trader;
                }

                if (tm.QC.@operator != null)
                {
                    NewMainRow["operator"] = tm.QC.@operator;
                    this.txtOperator.Text = tm.OperatorName;
                }

                NewMainRow["createTime"] = tm.QC.createTime;

                if (tm.QC.mender != null)
                {
                    NewMainRow["mender"] = tm.QC.mender;
                    NewMainRow["updateTime"] = tm.QC.updateTime;
                    this.txtMender.Text = tm.QC.mender.ToString();
                }

                if (tm.QC.assessor != null)
                    NewMainRow["assessor"] = tm.QC.assessor;
                this.txtAssessor.Text = tm.AssessorName;

                if (tm.QC.verifyTime != null)
                    NewMainRow["verifyTime"] = tm.QC.verifyTime;

                NewMainRow["status"] = tm.QC.status;
                this.txtStatus.Text = tm.QC.status;

                NewMainRow["memo"] = tm.QC.memo;
                this.txtMemo.Text = tm.QC.memo;

                //NewMainRow["code"] = tm.QC.code;
                NewMainRow["isVerify"] = tm.QC.isVerify;

                tMain.Rows.Add(NewMainRow);
            }
            #endregion

            #region
            if (td != null)
            {
                //this.gvQCDetail.
                for (int i = 0; i < td.Count(); i++)
                {
                    int j = this.gvQCDetail.Rows.Add();
                    this.gvQCDetail.Rows[j].Cells["id"].Value = td[i].QCDetail.id;
                    this.gvQCDetail.Rows[j].Cells["prevId"].Value = td[i].QCDetail.prevId;
                    this.gvQCDetail.Rows[j].Cells["prevType"].Value = td[i].QCDetail.prevType;
                    this.gvQCDetail.Rows[j].Cells["qc"].Value = td[i].QCDetail.qc;
                    this.gvQCDetail.Rows[j].Cells["qcCode"].Value = td[i].QCDetail.qcCode;
                    this.gvQCDetail.Rows[j].Cells["prevCode"].Value = td[i].QCDetail.prevCode;
                    this.gvQCDetail.Rows[j].Cells["material"].Value = td[i].QCDetail.material;
                    this.gvQCDetail.Rows[j].Cells["materialCode"].Value = td[i].QCDetail.materialCode;
                    this.gvQCDetail.Rows[j].Cells["materialName"].Value = td[i].MaterialName;
                    this.gvQCDetail.Rows[j].Cells["specs"].Value = td[i].QCDetail.specs;
                    this.gvQCDetail.Rows[j].Cells["checkNum"].Value = td[i].QCDetail.checkNum;
                    this.gvQCDetail.Rows[j].Cells["deliveryNum"].Value = td[i].QCDetail.deliveryNum;
                    this.gvQCDetail.Rows[j].Cells["qcResult"].Value = td[i].QCDetail.qcResult;
                    this.gvQCDetail.Rows[j].Cells["QcResultName"].Value = td[i].QCResultName + "[" + td[i].QCDetail.qcResult + "]";
                    this.gvQCDetail.Rows[j].Cells["FPY"].Value = td[i].QCDetail.FPY;
                    this.gvQCDetail.Rows[j].Cells["operator"].Value = td[i].QCDetail.@operator;
                    this.gvQCDetail.Rows[j].Cells["OperatorName"].Value = td[i].OperatorName;
                    this.gvQCDetail.Rows[j].Cells["craftComment"].Value = td[i].QCDetail.craftComment;
                    this.gvQCDetail.Rows[j].Cells["traderComment"].Value = td[i].QCDetail.traderComment;
                    this.gvQCDetail.Rows[j].Cells["conclusion"].Value = td[i].QCDetail.conclusion;
                    this.gvQCDetail.Rows[j].Cells["memo"].Value = td[i].QCDetail.memo;
                    this.gvQCDetail.Rows[j].Cells["refundNum"].Value = td[i].QCDetail.refundNum;
                    this.gvQCDetail.Rows[j].Cells["inNum"].Value = td[i].QCDetail.inNum;
                    this.gvQCDetail.Rows[j].Cells["notInNum"].Value = td[i].QCDetail.notInNum;

                    XQCProblem[] xqcp = BaseDataProxy.GetXQCProblems(td[i].QCDetail.id);
                    for (int n = 0; n < xqcp.Count(); n++)
                    {
                        int m = this.gvQCPromble.Rows.Add();
                        this.gvQCPromble.Rows[m].Cells["qcDetail"].Value = xqcp[n].QCProblem.qcDetail;
                        this.gvQCPromble.Rows[m].Cells["num"].Value = xqcp[n].QCProblem.num;
                        this.gvQCPromble.Rows[m].Cells["qcProblemType"].Value = xqcp[n].QCProblem.qcProblemType;
                        this.gvQCPromble.Rows[m].Cells["name"].Value = xqcp[n].ProblemName + "[" + xqcp[n].QCProblem.qcProblemType + "]";
                        this.gvQCPromble.Rows[m].Cells["isScrap"].Value = xqcp[n].IsScrap;                    
                    }

                }
            }
            #endregion

            setReadOnly(true);

            if (this.txtStatus.Text.ToString() == "已批")
            {
                //审批后,不允许再修改
                EditStatus = Common.BillOperateType.View;
                SetControlsStatus(false);
                this.btnSave.Enabled = false;
                this.btnDelete.Enabled = false;
                return;
            }
            else if (this.txtStatus.Text.ToString() == "未批")
            {
                //未审批,允许再修改
                EditStatus = Common.BillOperateType.Update;
                SetControlsStatus(true);
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = true;
            }
        }

        private void gvQCDetail_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //this.gvQCDetail.Rows[e.RowIndex].HeaderCell.Value = Convert.ToString(e.RowIndex + 1);//显示行号，也可以设置成显示其他信息 
        }

        private void gvQCPromble_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //this.gvQCPromble.Rows[e.RowIndex].HeaderCell.Value = Convert.ToString(e.RowIndex + 1);//显示行号，也可以设置成显示其他信息 

        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            //SelectBillFrm frm = new SelectBillFrm();
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.DH, "DH", false);
            //frm.ShowDialog();
            //if (frm.SelectBills.Count > 0)
            //{
            //    SelectBill(frm.SelectBills[0].BillId);
            //}
            //setReadOnly();
        }

        private void SelectBill(int BillId)
        {
            XOrder tm = BaseDataProxy.GetXOrder(BillId);
            XOrderDetail[] td = BaseDataProxy.GetXOrderDetails(BillId);

            #region  清除表中原来的记录
            this.gvQCDetail.AllowUserToDeleteRows = true;
            if (gvQCDetail.Rows.Count > 0)
            {
                for (int i = gvQCDetail.Rows.Count - 1; i >= 0; i--)
                {
                    gvQCDetail.Rows.RemoveAt(i);
                }
            }
            this.gvQCDetail.AllowUserToDeleteRows = false;
            #endregion

            this.gvQCDetail.AllowUserToAddRows = true;
            if (tm != null && td != null)
            {
                for (int i = 0; i < td.Count(); i++)
                {
                    int j = gvQCDetail.Rows.Add();
                    //this.gvQCDetail.Rows[j].Cells["qcCode"].Value = td[i].OrderDetail.q;
                    this.gvQCDetail.Rows[j].Cells["material"].Value = td[i].OrderDetail.material;
                    this.gvQCDetail.Rows[j].Cells["materialCode"].Value = td[i].OrderDetail.materialCode;
                    this.gvQCDetail.Rows[j].Cells["MaterialName"].Value = td[i].MaterialName;
                    this.gvQCDetail.Rows[j].Cells["specs"].Value = td[i].OrderDetail.specs;
                    this.gvQCDetail.Rows[j].Cells["prevId"].Value = td[i].OrderDetail.id;
                    this.gvQCDetail.Rows[j].Cells["PrevCode"].Value = td[i].OrderDetail.orderCode;//源单据号
                    this.gvQCDetail.Rows[j].Cells["prevType"].Value = BZSC.Common.EnumCommon.BillType.DH.ToString();  //"DHD";
                    this.gvQCDetail.Rows[j].Cells["deliveryNum"].Value = td[i].OrderDetail.num - (td[i].OrderDetail.qcNum ?? 0);//默认：交货数量=订单数量-已质检数量
                    this.gvQCDetail.Rows[i].Cells["refundNum"].Value = 0;
                }
                computer();
            }

            this.gvQCDetail.AllowUserToAddRows = false;

            if (this.txtStatus.Text.ToString() == "已审批")
            {
                //审批后,不允许再修改
                EditStatus = Common.BillOperateType.View;
                SetControlsStatus(false);
                return;
            }
            else if (this.txtStatus.Text.ToString() == "未批" && EditStatus != Common.BillOperateType.Add)
            {
                //未审批,允许再修改
                EditStatus = Common.BillOperateType.Update;
                SetControlsStatus(true);
            }
        }

        private void SelectBillSCD(int BillId)
        {
            //XPrdnMaterial 
            XProduction tm = BaseDataProxy.GetXProduction(BillId);
            XPrdnDetail[] td = BaseDataProxy.GetXPrdnDetails(BillId);

            #region  清除表中原来的记录
            this.gvQCDetail.AllowUserToDeleteRows = true;
            if (gvQCDetail.Rows.Count > 0)
            {
                for (int i = gvQCDetail.Rows.Count - 1; i >= 0; i--)
                {
                    gvQCDetail.Rows.RemoveAt(i);
                }
            }
            this.gvQCDetail.AllowUserToDeleteRows = false;
            #endregion
            this.gvQCDetail.AllowUserToAddRows = true;
            if (tm != null && td != null)
            {
                for (int i = 0; i < td.Count(); i++)
                {
                    int j = gvQCDetail.Rows.Add();
                    //this.gvQCDetail.Rows[j].Cells["qcCode"].Value = td[i].OrderDetail.q;
                    this.gvQCDetail.Rows[j].Cells["material"].Value = td[i].PrdnDetail.material;
                    this.gvQCDetail.Rows[j].Cells["materialCode"].Value = td[i].PrdnDetail.materialCode;
                    this.gvQCDetail.Rows[j].Cells["MaterialName"].Value = td[i].MaterialName;
                    this.gvQCDetail.Rows[j].Cells["specs"].Value = td[i].PrdnDetail.specs;
                    this.gvQCDetail.Rows[j].Cells["prevId"].Value = td[i].PrdnDetail.id;
                    this.gvQCDetail.Rows[j].Cells["PrevCode"].Value = td[i].PrdnDetail.prdnCode;//源单据号
                    this.gvQCDetail.Rows[j].Cells["prevType"].Value = BZSC.Common.EnumCommon.BillType.SCD.ToString(); //"SCD";
                    this.gvQCDetail.Rows[j].Cells["deliveryNum"].Value = td[i].PrdnDetail.finishNum;// td[i].PrdnDetail.num - (td[i].PrdnDetail.qcNum ?? 0);//默认：交货数量=订单数量-已质检数量
                    this.gvQCDetail.Rows[i].Cells["refundNum"].Value = 0;

                }
                computer();
            }

            this.gvQCDetail.AllowUserToAddRows = false;

            if (this.txtStatus.Text.ToString() == "已审批")
            {
                //审批后,不允许再修改
                EditStatus = Common.BillOperateType.View;
                SetControlsStatus(false);
                return;
            }
            else if (this.txtStatus.Text.ToString() == "未批" && EditStatus != Common.BillOperateType.Add)
            {
                //未审批,允许再修改
                EditStatus = Common.BillOperateType.Update;
                SetControlsStatus(true);
            }

        }

        private void traderSelector_SelectorClick(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            TraderFrm frm = new TraderFrm();
            frm.Text = "选择报检单位";
            frm.SearchSupplierMode(); //.SetTraderAsSupplier();
            

            if (frm.ShowDialog() == DialogResult.OK)
            {
                edtTrader.SetSelected(frm.SelectorItem);
                tMain.Rows[0]["trader"] = Common.StringToInt(frm.SelectorItem.Value);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.toolStrip1.Focus();
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update) & (EditStatus == Common.BillOperateType.Delete))
                return;
            if (tMain.Rows.Count <= 0)
            {
                MessageBox.Show("无单据要保存。。。");
                return;
            }

            if (EditStatus == Common.BillOperateType.Add)
            {
                if (string.IsNullOrEmpty(tMain.Rows[0]["code"].ToString()))
                {
                    this.txtDjh.Text = BaseDataProxy.GetSerialNo(1, BillPrefix, 4, true, true, true);
                    tMain.Rows[0]["code"] = this.txtDjh.Text;
                }
                tMain.Rows[0]["operator"] = SysLoginUserInfo.UserId;
                tMain.Rows[0]["createTime"] = DateTime.Now;
                tMain.Rows[0]["qcDate"] = this.dtpqcDate.Value;
                
                btnConfirm.Enabled = true;
            }
            else
            {
                tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
                //this.txtMender.Text = SysLoginUserInfo.UserName;
                tMain.Rows[0]["updateTime"] = DateTime.Now;
            }

            if (this.txtJyType.Text == "采购检验")
                tMain.Rows[0]["type"] = "CGZJ";
            else if (this.txtJyType.Text == "生产检验")
                tMain.Rows[0]["type"] = "SCZJ";

            tMain.Rows[0]["memo"] = this.txtMemo.Text;

            tMain.AcceptChanges();
            tDetail.AcceptChanges();

            TB_QC TB_QC = OTConverter.ConvertToObject<TB_QC>(tMain.Rows[0]);

            //TB_RecvMaterial tbRecvMaterial = OTConverter.ConvertToObject<TB_RecvMaterial>(tMain.Rows[0]);

            if (EditStatus == Common.BillOperateType.Add || EditStatus == Common.BillOperateType.Update)
            {
                #region
                tDetail.Clear();
                for (int i = 0; i < this.gvQCDetail.Rows.Count; i++)
                {
                    if (gvQCDetail.RCText(i, "checknum").ToString() == "" || gvQCDetail.RCText(i, "deliveryNum").ToString() == "")
                    {
                        MessageBox.Show("检查数量，交货数量不能为空！(^_^)");
                        return;
                    }
                    DataRow NewDetailRow = tDetail.NewRow();

                    if (this.gvQCDetail.RCText(i, "id") != "")
                        NewDetailRow["id"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "id"));
                    //NewDetailRow["qc"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "qc"));
                    NewDetailRow["qcCode"] = this.txtDjh.Text;
                    NewDetailRow["material"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "material"));
                    NewDetailRow["materialCode"] = this.gvQCDetail.RCText(i, "materialCode");

                    NewDetailRow["checkNum"] = Convert.ToDecimal(this.gvQCDetail.RCText(i, "checkNum"));
                    NewDetailRow["deliveryNum"] = Convert.ToDecimal(this.gvQCDetail.RCText(i, "deliveryNum"));
                    if (gvQCDetail.RCText(i, "qcResult") != "")
                        NewDetailRow["qcResult"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "qcResult"));
                    if (gvQCDetail.RCText(i, "FPY") != "")
                        NewDetailRow["FPY"] = Convert.ToDecimal(this.gvQCDetail.RCText(i, "FPY"));
                    //if (gvQCDetail.RCText(i, "operator") != "")
                    //    NewDetailRow["operator"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "operator"));
                    NewDetailRow["operator"] = SysLoginUserInfo.UserId;

                    NewDetailRow["level"] = this.gvQCDetail.RCText(i, "level");
                    NewDetailRow["craftComment"] = this.gvQCDetail.RCText(i, "craftComment");
                    NewDetailRow["traderComment"] = this.gvQCDetail.RCText(i, "traderComment");
                    NewDetailRow["conclusion"] = this.gvQCDetail.RCText(i, "conclusion");
                    //NewDetailRow["tcDetail"] =
                    NewDetailRow["specs"] = this.gvQCDetail.RCText(i, "specs");

                    if (gvQCDetail.RCText(i, "prevId") != "")
                        NewDetailRow["prevId"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "prevId"));
                    NewDetailRow["prevCode"] = this.gvQCDetail.RCText(i, "prevCode");
                    NewDetailRow["prevType"] = this.gvQCDetail.RCText(i, "prevType");
                    NewDetailRow["memo"] = this.gvQCDetail.RCText(i, "memo");

                    if (this.gvQCDetail.RCText(i, "refundNum") != "")//质检退货数
                        NewDetailRow["refundNum"] = Convert.ToDecimal(this.gvQCDetail.RCText(i, "refundNum"));
                    if (this.gvQCDetail.RCText(i, "inNum") != "")//质检入库数
                        NewDetailRow["inNum"] = Convert.ToDecimal(this.gvQCDetail.RCText(i, "inNum"));
                    if (this.gvQCDetail.RCText(i, "notInNum") != "")//质检未入库数
                        NewDetailRow["notInNum"] = Convert.ToDecimal(this.gvQCDetail.RCText(i, "notInNum"));

                    tDetail.Rows.Add(NewDetailRow);
                }
                List<TB_QCDetail> lsRecvDetail = OTConverter.ConvertTableToObject<TB_QCDetail>(tDetail);
                TB_QCDetail[] TB_QCDetail = lsRecvDetail.ToArray();
                #endregion

                tDetail.AcceptChanges();
                TB_QC.TB_QCDetail = TB_QCDetail;

                #region 问题
                foreach (TB_QCDetail qcd in TB_QCDetail)
                {
                    tQCPr.Rows.Clear();
                    for (int i = 0; i < gvQCPromble.Rows.Count - 1; i++)
                    {
                        if (this.gvQCPromble.RCText(i, "num") == "")
                        {
                            MessageBox.Show("请正确输入不良数量！");
                            return;
                        }
                        if ((qcd.prevId == Convert.ToInt32(this.gvQCPromble.Rows[i].Cells["QCDetailId"].Value)) || (this.gvQCPromble.Rows[i].Cells["qcDetail"].Value != null && qcd.id == Convert.ToInt32(this.gvQCPromble.Rows[i].Cells["qcDetail"].Value)))
                        {
                            DataRow NewDetailRow = tQCPr.NewRow();
                            //NewDetailRow["qcDetail"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "prevId")); // 新增时无明细id
                            NewDetailRow["num"] = Convert.ToInt32(this.gvQCPromble.RCText(i, "num")); ;
                            NewDetailRow["qcproblemType"] = Convert.ToInt32(this.gvQCPromble.RCText(i, "qcproblemType")); ;
                            //NewDetailRow["name"] = Convert.ToInt32(this.gvQCDetail.RCText(i, "prevId")); //名字不需要保存
                            tQCPr.Rows.Add(NewDetailRow);
                        }
                    }
                    List<TB_QCProblem> lsTB_QCProblem = OTConverter.ConvertTableToObject<TB_QCProblem>(tQCPr);
                    TB_QCProblem[] qcps = lsTB_QCProblem.ToArray();
                    qcd.TB_QCProblem = qcps;
                }
                #endregion

                if (EditStatus == Common.BillOperateType.Add)
                {
                    tb_qc_id = this.BaseDataProxy.AddQC(TB_QC);
                    tMain.Rows[0]["id"] = tb_qc_id;
                }
                else if (EditStatus == Common.BillOperateType.Update)
                    this.BaseDataProxy.UpdateQC(TB_QC);

                EditStatus = Common.BillOperateType.Update;
                MessageBox.Show("已成功保存单据.");
            }
        }

        private void gvQCDetail_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            else 
            {
                if (EditStatus == Common.BillOperateType.Add)
                {
                    int j = e.RowIndex;
                    for (int i = 0; i < gvQCPromble.RowCount - 1; i++)
                    {
                        if (this.gvQCPromble.Rows[i].Cells["QCDetailId"].Value.ToString() == this.gvQCDetail.Rows[j].Cells["prevId"].Value.ToString())
                        {
                            gvQCPromble.SetDgRowDefaultBackColor(i, Color.Tomato);
                            //this.gvQCPromble.FirstDisplayedScrollingRowIndex = e.RowIndex;
                        }
                        else
                            gvQCPromble.SetDgRowDefaultBackColor(i, Color.White);
                    }
                }
                else 
                {
                     int j = e.RowIndex;
                     for (int i = 0; i < gvQCPromble.RowCount - 1; i++)
                     {
                         if (this.gvQCPromble.Rows[i].Cells["qcDetail"].Value != null && this.gvQCDetail.Rows[j].Cells["id"].Value != null)
                         {
                             if (this.gvQCPromble.Rows[i].Cells["qcDetail"].Value.ToString() == this.gvQCDetail.Rows[j].Cells["id"].Value.ToString())
                             {
                                 gvQCPromble.SetDgRowDefaultBackColor(i, Color.Tomato);
                                 //this.gvQCPromble.FirstDisplayedScrollingRowIndex = e.RowIndex;
                             }
                             else
                                 gvQCPromble.SetDgRowDefaultBackColor(i, Color.White);
                         }
                         else if (this.gvQCPromble.Rows[i].Cells["QCDetailId"].Value != null && this.gvQCDetail.Rows[j].Cells["prevId"].Value != null)
                         {
                             if (this.gvQCPromble.Rows[i].Cells["QCDetailId"].Value.ToString() == this.gvQCDetail.Rows[j].Cells["prevId"].Value.ToString())
                             {
                                 gvQCPromble.SetDgRowDefaultBackColor(i, Color.Tomato);
                                 //this.gvQCPromble.FirstDisplayedScrollingRowIndex = e.RowIndex;
                             }
                             else
                                 gvQCPromble.SetDgRowDefaultBackColor(i, Color.White);
                         }
                     }
                }
            }
        }

        private void gvQCPromble_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.gvQCPromble);
            if (e.RowIndex >= 0 && gvQCDetail.CurrentCell.RowIndex >= 0 && (EditStatus == Common.BillOperateType.Add || EditStatus == Common.BillOperateType.Update))
                this.gvQCPromble.Rows[e.RowIndex - 1].Cells["QCDetailId"].Value = this.gvQCDetail.Rows[gvQCDetail.CurrentCell.RowIndex].Cells["prevId"].Value;
        
        }

        private void gvQCPromble_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //return;
        }

        private void gvQCPromble_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int irow = e.RowIndex;
            int icol = e.ColumnIndex;
            if (irow < 0 || icol < 0)
            {
                return;
            }
            else if (gvQCPromble.Columns[icol].Name == "name")
            {
                int a = this.gvQCPromble.RCText(irow, "name").IndexOf('[');
                int b = this.gvQCPromble.RCText(irow, "name").IndexOf(']');
                int c = 0;

                if (a > 0 && b > a)
                {
                    c = Convert.ToInt32(this.gvQCPromble.RCText(irow, "name").Substring(a + 1, b - a - 1));
                    this.gvQCPromble.Rows[irow].Cells["qcProblemType"].Value = c;
                }

                if (!bGraph && (irow != gvQCPromble.Rows.Count - 2))
                {
                    bGraph = true;
                    if (MessageBox.Show("以下是否设为相同？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        for (int i = gvQCPromble.Rows.Count - 2; irow < i; i--)
                        {
                            gvQCPromble.Rows[i].Cells["name"].Value = gvQCPromble.RCText(irow, icol);
                            this.gvQCPromble.Rows[i].Cells["qcProblemType"].Value = c;
                        }
                    }
                    else
                    {
                        bGraph = false;
                        return;
                    }
                    bGraph = false;
                }

            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.txtStatus.Text == "已审批")
            {
                MessageBox.Show("无法删除已审批单据.");
                return;
            }

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            this.gvQCDetail.CancelEdit();

            if (EditStatus == Common.BillOperateType.Add)
            {
                tMain.Rows.Clear();
                tDetail.Rows.Clear();
                SetNull();
                SetControlsStatus(true);
                return;
            }

            //(EditStatus == Common.BillOperateType.Update)
            int BillId = (int)tMain.Rows[0]["id"];

            if (MessageBox.Show("确认删除整张单吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (BaseDataProxy.DeleteQC(BillId))
                {

                    //dtpData.Rows.Clear();
                    for (int i = gvQCDetail.Rows.Count - 1; i >= 0; i--)
                    {
                        gvQCDetail.Rows.RemoveAt(i);
                    }
                    for (int i = this.gvQCPromble.Rows.Count - 2; i >= 0; i--)
                    {
                        gvQCPromble.Rows.RemoveAt(i);
                    }
                    SetNull();
                    SetControlsStatus(true);
                    MessageBox.Show("已成功删除单据.");
                }
                else
                    MessageBox.Show("无法删除单据.");
            }
        }

        private void gvQCDetail_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.gvQCDetail);
            bindQCResult();
        }

        private void computer()
        {
            for (int i = 0; i < gvQCDetail.Rows.Count; i++)
            {
                if (gvQCDetail.RCText(i, "refundNum") == "")
                    gvQCDetail.Rows[i].Cells["refundNum"].Value = 0;

                if (isNumber(gvQCDetail.RCText(i, "notInNum")) && isNumber(gvQCDetail.RCText(i, "deliveryNum")) && isNumber(gvQCDetail.RCText(i, "refundNum")))
                {
                    gvQCDetail.Rows[i].Cells["notInNum"].Value = Convert.ToDecimal(gvQCDetail.Rows[i].Cells["deliveryNum"].Value) - Convert.ToDecimal(gvQCDetail.Rows[i].Cells["refundNum"].Value);
                }
            }
        }

        private void gvQCDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int irow = e.RowIndex;
            int icol = e.ColumnIndex;
            if (irow < 0 || icol < 0)
            {
                return;
            }
            else if (gvQCDetail.Columns[icol].Name == "QcResultName")
            {
                int a = this.gvQCDetail.RCText(irow, "QcResultName").IndexOf('[');
                int b = this.gvQCDetail.RCText(irow, "QcResultName").IndexOf(']');
                int c = 0;

                if (a > 0 && b > a)
                {
                    c = Convert.ToInt32(this.gvQCDetail.RCText(irow, "QcResultName").Substring(a + 1, b - a - 1));
                    this.gvQCDetail.Rows[irow].Cells["qcResult"].Value = c;
                }

                if (!bGraph && (irow != gvQCDetail.Rows.Count - 1))
                {
                    bGraph = true;
                    if (MessageBox.Show("以下是否设为相同？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        for (int i = gvQCDetail.Rows.Count - 1; irow < i; i--)
                        {
                            gvQCDetail.Rows[i].Cells["QcResultName"].Value = gvQCDetail.RCText(irow, icol);
                            this.gvQCDetail.Rows[i].Cells["qcResult"].Value = c;
                        }
                    }
                    else
                    {
                        bGraph = false;
                        return;
                    }
                    bGraph = false;
                }

            }
            else if (gvQCDetail.Columns[icol].Name == "refundNum" || gvQCDetail.Columns[icol].Name == "deliveryNum")
            {
                //if (isNumber(this.gvQCDetail.RCText(irow, "notInNum")) && isNumber(gvQCDetail.RCText(irow, "deliveryNum")) && isNumber(gvQCDetail.RCText(irow, "refundNum")))
                //    gvQCDetail.Rows[irow].Cells["notInNum"].Value = Convert.ToDecimal(gvQCDetail.Rows[irow].Cells["deliveryNum"].Value) - Convert.ToDecimal(gvQCDetail.Rows[irow].Cells["refundNum"].Value);


                if (isNumber(this.gvQCDetail.RCText(irow,"notInNum")) && isNumber(gvQCDetail.RCText(irow,"deliveryNum")) && isNumber(gvQCDetail.RCText(irow,"refundNum")))
                    gvQCDetail.Rows[irow].Cells["notInNum"].Value = Convert.ToDecimal(gvQCDetail.Rows[irow].Cells["deliveryNum"].Value) - Convert.ToDecimal(gvQCDetail.Rows[irow].Cells["refundNum"].Value);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            //
        }

        private void btnUnConfirm_Click(object sender, EventArgs e)
        {
            //
        }

        private void btnConfirmOk_Click(object sender, EventArgs e)
        {
            if (tMain.Rows.Count <= 0 || this.gvQCDetail.Rows.Count <= 0)
                return;
            tMain.Rows[0]["assessor"] = SysLoginUserInfo.UserId;
            tMain.Rows[0]["verifyTime"] = DateTime.Now;
            tMain.Rows[0]["status"] = "已批";
            tMain.AcceptChanges();

            int BillId = (int)tMain.Rows[0]["id"];

            VerifyBillResult ver = BaseDataProxy.VerifyBill("ZJ", BillId, SysLoginUserInfo.UserId, true);

            if (ver.Pass)
            {
                this.txtStatus.Text = "已批";
                this.txtAssessor.Text = SysLoginUserInfo.UserName;
                EditStatus = Common.BillOperateType.None;
                SetControlsStatus(false);
                this.btnSave.Enabled = false;
                this.btnDelete.Enabled = false;
            }
            else
            {
                this.txtStatus.Text = "";
                this.txtAssessor.Text = "";
            }
            MessageBox.Show(ver.Message);
        }

        private void btnConfirmNo_Click(object sender, EventArgs e)
        {
            if (tMain.Rows.Count <= 0 || gvQCDetail.Rows.Count <= 0)
                return;
            tMain.Rows[0]["assessor"] = DBNull.Value;
            tMain.Rows[0]["verifyTime"] = DBNull.Value;
            tMain.Rows[0]["status"] = "未批";
            tMain.AcceptChanges();

            int BillId = (int)tMain.Rows[0]["id"];

            VerifyBillResult ver = BaseDataProxy.VerifyBill("ZJ", BillId, SysLoginUserInfo.UserId, false);

            if (ver.Pass)
            {
                this.txtStatus.Text = "未批";
                this.txtAssessor.Text = "";
                SetControlsStatus(true);
                EditStatus = Common.BillOperateType.Update;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = true;
                //this.txtStatus.Text = "已批";
                //this.txtAssessor.Text = SysLoginUserInfo.UserName;
            }
            else
            {

            }
            MessageBox.Show(ver.Message);
        }

        private void gvQCDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //return;
        }

        private void 来自采购单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.CG;
            frm.SearchMode = GRWL.BZSC.UI.FindBillFrm.SearchModeType.source;
            frm.Text = "单据查找(来自采购单)";
            frm.status = "已批";
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    //bGraph = true;
                    //QRecvMaterial qrecv = OTConverter.ConvertToObject<QRecvMaterial>(frm.SelectedItems);
                    QOrder qorder = OTConverter.ConvertToObject<QOrder>(frm.SelectedItems);
                    SelectBill(qorder.Id);
                }
            }

            //SelectBillFrm frm = new SelectBillFrm();
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.CG, "CG", false);
            //frm.ShowDialog();
            //if (frm.SelectBills.Count > 0)
            //{
            //    SelectBill(frm.SelectBills[0].BillId);
            //}

            setReadOnly(true);
            this.txtJyType.Text = "采购检验";
            tMain.Rows[0]["type"] = "CGZJ";
        }

        private void 来自生产单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.SCD;
            frm.SearchMode = GRWL.BZSC.UI.FindBillFrm.SearchModeType.source;
            frm.Text = "单据查找(来自生产单)";
            frm.status = "已批";

            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    QProduction qpro=OTConverter.ConvertToObject<QProduction>(frm.SelectedItems);
                    SelectBillSCD(qpro.Id);
                }
            }
            setReadOnly(true);
            this.txtJyType.Text = "生产检验";
            tMain.Rows[0]["type"] = "SCZJ";
        }

        private void gvQCDetail_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.gvQCDetail);
        }

        private void gvQCPromble_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.gvQCPromble);
        }

        TextBox control = null;

        private void gvQCDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.gvQCDetail.Columns[this.gvQCDetail.CurrentCell.ColumnIndex].Name == "QcResultName" || this.gvQCDetail.Columns[this.gvQCDetail.CurrentCell.ColumnIndex].Name == "OperatorName")
                return;
            e.CellStyle.BackColor = Color.AliceBlue;//设置编译时的颜色
            control = (TextBox)e.Control;
            switch (this.gvQCDetail.CurrentCell.ColumnIndex)
            {
                case 10:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
                case 11:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
                case 12:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
                case 13:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
            }
        }

        private void gvQCPromble_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.gvQCPromble.Columns[this.gvQCPromble.CurrentCell.ColumnIndex].Name == "name")
                return;
            e.CellStyle.BackColor = Color.AliceBlue;//设置编译时的颜色
            control = (TextBox)e.Control;
            switch (this.gvQCPromble.CurrentCell.ColumnIndex)
            {
                case 1:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
            }
        }

        private void control_KeyPress(object sender, KeyPressEventArgs e)
        {
            ////限制只能输入0-9的数字，退格键，小数点
            if (this.gvQCDetail.CurrentCell.ColumnIndex == 10 || this.gvQCDetail.CurrentCell.ColumnIndex == 11 || this.gvQCDetail.CurrentCell.ColumnIndex == 12 || this.gvQCDetail.CurrentCell.ColumnIndex == 13)
            {
                if (((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57) || e.KeyChar == 8 || e.KeyChar == 46)
                { }
                else
                    e.Handled = true;
            }
        }
    }
}
